<template>
  <div class="maintenance-report-container">
    <div class="maintenance-report-header">
      <div class="header-actions">
        <el-button type="primary" plain size="small" @click="goBack">
          <el-icon><Back /></el-icon> 返回首页
        </el-button>
      </div>
      <h1>信息反馈</h1>
      <p>反馈青岛景点问题信息</p>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧地图区域 -->
      <el-col :span="16">
        <el-card class="map-card">
          <div id="scenicMapView" class="map-container"></div>
        </el-card>
      </el-col>

      <!-- 右侧功能区域 -->
      <el-col :span="8">
        <!-- 景区选择 -->
        <el-card class="area-select-card">
          <template #header>
            <div class="card-header">
              <span>景区选择</span>
            </div>
          </template>

          <div class="area-tabs">
            <el-tabs v-model="activeArea" @tab-click="handleAreaChange">
              <el-tab-pane label="胶南灵山岛景区" name="erdihu"></el-tab-pane>
            <el-tab-pane label="大公岛景区" name="yunmen"></el-tab-pane>
            <el-tab-pane label="大泽山景区" name="bailang"></el-tab-pane>
            <el-tab-pane label="崂山景区" name="xiashan"></el-tab-pane>
            <el-tab-pane label="胶州艾山景区" name="binhai"></el-tab-pane>
            <el-tab-pane label="马山景区" name="mihe"></el-tab-pane>
            </el-tabs>
          </div>
        </el-card>

        <!-- 保护区列表 -->
        <el-card class="scenic-list-card">
          <template #header>
            <div class="card-header">
              <span>景点列表</span>
              <el-input
                v-model="searchQuery"
                placeholder="搜索景点名称"
                prefix-icon="Search"
                clearable
                @input="handleSearch"
                size="small"
                style="width: 200px"
              />
            </div>
          </template>

          <el-table
            :data="tableData"
            style="width: 100%"
            v-loading="loading"
            @row-click="handleRowClick"
            height="300"
          >
            <el-table-column prop="attributes.OBJECTID" label="ID" width="80" />
            <el-table-column prop="attributes.ScenicName" label="景点名称" />
            <el-table-column prop="attributes.ScenicType" label="类型" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  @click.stop="openReportForm(scope.row)"
                >
                  上报
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 已选择保护区信息 -->
        <el-card v-if="selectedFeatureId" class="selected-feature-card">
          <template #header>
            <div class="card-header">
              <span>已选择景点</span>
            </div>
          </template>

          <div class="selected-feature-info">
            <h3>{{ selectedFeatureName }}</h3>
            <p v-if="selectedFeatureType">类型: {{ selectedFeatureType }}</p>
            <el-button type="primary" @click="openReportForm(selectedFeature)">
              <el-icon><Tools /></el-icon> 上报维修信息
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <!-- 维修上报表单抽屉 -->
  <el-drawer
    v-model="showReportDrawer"
    title="上报维修信息"
    direction="rtl"
    size="500px"
  >
    <el-form
      v-if="currentFeature"
      ref="reportFormRef"
      :model="reportForm"
      :rules="reportRules"
      label-width="100px"
      class="report-form"
    >
      <el-form-item label="景点名称">
        <el-input v-model="currentFeature.attributes.ScenicName" disabled />
      </el-form-item>

      <el-form-item label="问题标题" prop="title">
        <el-input v-model="reportForm.title" placeholder="请输入问题标题" />
      </el-form-item>

      <el-form-item label="问题描述" prop="description">
        <el-input
          v-model="reportForm.description"
          type="textarea"
          :rows="4"
          placeholder="请详细描述问题"
        />
      </el-form-item>

      <el-form-item label="问题严重性" prop="severity">
        <el-select v-model="reportForm.severity" placeholder="请选择问题严重性" style="width: 100%">
          <el-option label="轻微" value="minor" />
          <el-option label="中等" value="moderate" />
          <el-option label="严重" value="critical" />
        </el-select>
      </el-form-item>

      <el-form-item label="问题图片">
        <el-upload
          class="upload-demo"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :limit="1"
          :on-change="handlePhotoChange"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitReport">提交上报</el-button>
        <el-button @click="showReportDrawer = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup lang="ts">
declare global {
  interface Window {
    _tempFeatures: __esri.Graphic[]
  }
}
import { ref, onMounted, reactive } from 'vue'
import { Back, Search, Tools, Plus } from '@element-plus/icons-vue'
import { ElMessage,  type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import { gaodeLayer } from '@/utils/GaoDeBaseLayer'

// 用户存储和路由
const userStore = useUserStore()
const router = useRouter()

// 地图和图层
let view: __esri.MapView
let featureLayer: __esri.FeatureLayer

// 状态变量
const loading = ref(true)
const searchQuery = ref('')
const tableData = ref<any[]>([])
const selectedFeatureId = ref<number | null>(null)
const selectedFeatureName = ref('')
const selectedFeatureType = ref('')
const selectedFeature = ref<any>(null)
const showReportDrawer = ref(false)
const currentFeature = ref<any>(null)
const reportFormRef = ref<FormInstance>()

// 当前选中的景区
const activeArea = ref('erdihu') // 默认胶南灵山岛保护区

// 各个景区的中心坐标
const areaCenters = {
  erdihu: [120.179558,35.765965], // 胶南灵山岛坐标
  yunmen: [120.503415,35.967122], // 大公岛坐标
  bailang: [120.022251,37.00615], // 大泽山坐标
  xiashan: [120.605305,36.198964], // 崂山坐标
  binhai: [119.93718,36.121442], // 胶州艾山坐标
  mihe: [120.651138,36.340289] // 马山坐标
}

// 维修上报表单
const reportForm = reactive({
  title: '',
  description: '',
  severity: '',
  photoBase64: '',
  reportDate: new Date().toISOString(),
  status: 'pending',
  reporter: userStore.currentUser?.username || '',
  comments: [] as { user: string; text: string; date: string }[]
})

// 表单验证规则
const reportRules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入问题标题', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  severity: [
    { required: true, message: '请选择问题严重性', trigger: 'change' }
  ]
})

// 查询景点数据
const queryFeatures = async () => {
  if (!featureLayer) return

  loading.value = true
  try {
    // 创建查询
    const query = featureLayer.createQuery()

    // 根据当前选中的景区过滤
    const currentAreaName = getCurrentAreaName()
    let whereClause = `OwnerScenic = '${currentAreaName}' OR OwnerScenic IS NULL`
    console.log('whereClause:', whereClause)
    // 如果有搜索条件，添加到查询中
    if (searchQuery.value) {
      whereClause += ` AND ScenicName LIKE '%${searchQuery.value}%'`
    }

    query.where = whereClause
    query.outFields = ['*']

    // 执行查询
    const result = await featureLayer.queryFeatures(query)
    console.log('查询结果：', result)

    // 存储原始的ESRI要素对象到非响应式变量中
    window._tempFeatures = result.features

    // 将要素ID和属性数据存储到响应式变量中
    tableData.value = result.features.map((feature, index) => ({
      // 存储原始要素的索引，供后续使用
      _index: index,
      // 复制属性数据
      attributes: { ...feature.attributes },
    }))
  } catch (error) {
    console.error('查询景点数据失败', error)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 初始化地图
const initMap = async () => {
  // 创建地图实例
  const map = new Map({
    basemap: 'streets-vector',
  })

  // 创建地图视图
  view = new MapView({
    container: 'scenicMapView',
    map: map,
    center: areaCenters[activeArea.value as keyof typeof areaCenters], // 根据当前选中的景区设置中心点
    zoom: 13,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false,
      },
    },
  })

  // 创建景点要素图层
  featureLayer = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/ScenicPointLayer/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'unique-value',
      field: 'ScenicType',
      uniqueValueInfos: [
        {
          value: '自然景观',
          symbol: {
            type: 'simple-marker',
            color: [34, 139, 34],
            size: 8,
            outline: { color: 'white', width: 1 }
          }
        },
        {
          value: '人文景观',
          symbol: {
            type: 'simple-marker',
            color: [30, 144, 255],
            size: 8,
            outline: { color: 'white', width: 1 }
          }
        },
        {
          value: '历史遗迹',
          symbol: {
            type: 'simple-marker',
            color: [255, 140, 0],
            size: 8,
            outline: { color: 'white', width: 1 }
          }
        },
        {
          value: '休闲娱乐',
          symbol: {
            type: 'simple-marker',
            color: [255, 20, 147],
            size: 8,
            outline: { color: 'white', width: 1 }
          }
        },
        {
          value: '观景台',
          symbol: {
            type: 'simple-marker',
            color: [128, 128, 128],
            size: 8,
            outline: { color: 'white', width: 1 }
          }
        }
      ]
    },
    labelingInfo: [
      {
        symbol: {
          type: 'text',
          color: '#333333',
          haloColor: '#ffffff',
          haloSize: 2,
          font: {
            size: 10,
            weight: 'normal',
          },
        },
        labelPlacement: 'above-center',
        labelExpressionInfo: {
          expression: '$feature.ScenicName',
        },
        minScale: 50000,
        maxScale: 0,
      },
    ],
  })

  // 将图层添加到地图
  map.add(featureLayer)

  // 添加点击事件监听器以选择要素
  view.on('click', async (event) => {
    const hitResults = (await view?.hitTest(event))?.results as __esri.MapViewGraphicHit[]
    const feature = hitResults.find((result) => result.layer?.id === featureLayer?.id)?.graphic

    if (feature) {
      // 设置选中的要素ID和名称
      selectedFeatureId.value = feature.attributes.OBJECTID
      selectedFeatureName.value = feature.attributes.ScenicName
      selectedFeatureType.value = feature.attributes.ScenicType
      selectedFeature.value = {
        _index: window._tempFeatures.findIndex(f => f.attributes.OBJECTID === feature.attributes.OBJECTID),
        attributes: { ...feature.attributes }
      }

      // 添加高亮效果
      highlightFeatureOnMap(feature)
    }
  })

  // 加载要素数据
  await queryFeatures()
}

// 获取当前景区名称
const getCurrentAreaName = () => {
  switch (activeArea.value) {
    case 'erdihu':
      return '胶南灵山岛保护区'
    case 'yunmen':
      return '大公岛保护区'
    case 'bailang':
      return '大泽山保护区'
    case 'xiashan':
      return '崂山保护区'
    case 'binhai':
      return '胶州艾山保护区'
    case 'mihe':
      return '马山保护区'
    default:
      return ''
  }
}

// 处理景区切换
const handleAreaChange = () => {
  // 将地图中心移动到选中的景区
  view?.goTo({
    center: areaCenters[activeArea.value as keyof typeof areaCenters],
    zoom: 13,
  })

  // 重新加载数据
  queryFeatures()
}

// 处理搜索
const handleSearch = () => {
  queryFeatures()
}

// 处理表格行点击
const handleRowClick = (row: any) => {
  // 设置选中的要素ID和名称
  selectedFeatureId.value = row.attributes.OBJECTID
  selectedFeatureName.value = row.attributes.ScenicName
  selectedFeatureType.value = row.attributes.ScenicType
  selectedFeature.value = row

  // 从非响应式存储中获取原始要素
  const originalFeature = window._tempFeatures?.[row._index]
  highlightFeatureOnMap(originalFeature)
}

// 在地图上高亮显示要素
const highlightFeatureOnMap = (feature: any) => {
  if (!feature || !feature.geometry) return

  // 清除之前的高亮
  view?.graphics.removeAll()

  // 创建高亮符号
  const highlightSymbol = new SimpleMarkerSymbol({
    color: [255, 255, 255, 0.8],
    size: 16,
    outline: {
      color: [0, 122, 194],
      width: 3,
    },
  })

  // 创建高亮图形
  const highlightGraphic = new Graphic({
    geometry: feature.geometry,
    symbol: highlightSymbol,
  })

  // 添加到地图
  view?.graphics.add(highlightGraphic)

  // 将视图中心移动到要素位置
  view?.goTo({
    target: feature.geometry,
    zoom: 15,
  })
}

// 打开维修上报表单
const openReportForm = (feature: any) => {
  if (!feature) return

  // 重置表单
  reportForm.title = ''
  reportForm.description = ''
  reportForm.severity = ''
  reportForm.photoBase64 = ''
  reportForm.reportDate = new Date().toISOString()
  reportForm.status = 'pending'
  reportForm.reporter = userStore.currentUser?.username || ''
  reportForm.comments = []

  // 设置当前要素
  currentFeature.value = feature

  // 显示抽屉
  showReportDrawer.value = true
}

// 处理图片上传
const handlePhotoChange = (file: any) => {
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    reportForm.photoBase64 = reader.result as string
  }
}

// 提交维修上报
const submitReport = async () => {
  if (!reportFormRef.value) return

  await reportFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请完善表单信息')
      return
    }

    try {
      // 获取当前要素
      const feature = window._tempFeatures?.[currentFeature.value._index]
      if (!feature) {
        ElMessage.error('无法获取保护区信息')
        return
      }

      // 准备维修数据
      const maintenanceReport = {
        id: Date.now().toString(),
        title: reportForm.title,
        description: reportForm.description,
        severity: reportForm.severity,
        photoBase64: reportForm.photoBase64,
        reportDate: reportForm.reportDate,
        status: reportForm.status,
        reporter: reportForm.reporter,
        comments: reportForm.comments
      }

      // 获取现有的维修数据
      let maintenanceData = []
      if (feature.attributes.MaintanceDataJson) {
        try {
          maintenanceData = JSON.parse(feature.attributes.MaintanceDataJson)
        } catch (e) {
          console.error('解析现有维修数据失败', e)
          maintenanceData = []
        }
      }

      // 添加新的维修报告
      maintenanceData.push(maintenanceReport)

      // 更新要素
      const updateFeature = new Graphic({
        attributes: {
          OBJECTID: feature.attributes.OBJECTID,
          MaintanceDataJson: JSON.stringify(maintenanceData)
        }
      })

      const result = await featureLayer.applyEdits({
        updateFeatures: [updateFeature]
      })

      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('维修信息已上报')
        showReportDrawer.value = false
        await queryFeatures()
      } else {
        ElMessage.error('上报维修信息失败')
      }
    } catch (error) {
      console.error('上报维修信息失败', error)
      ElMessage.error('上报维修信息失败')
    }
  })
}

// 返回首页
const goBack = () => {
  router.push('/')
}

// 检查是否有指定的景点ID
const checkForSpecificPoint = async () => {
  const id = router.currentRoute.value.query.id
  if (id && featureLayer) {
    try {
      // 创建查询
      const query = featureLayer.createQuery()
      query.where = `OBJECTID=${id}`
      query.outFields = ['*']

      // 执行查询
      const result = await featureLayer.queryFeatures(query)

      if (result.features.length > 0) {
        const feature = result.features[0]

        // 设置选中的要素ID和名称
        selectedFeatureId.value = feature.attributes.OBJECTID
        selectedFeatureName.value = feature.attributes.ScenicName
        selectedFeatureType.value = feature.attributes.ScenicType
        selectedFeature.value = {
          _index: 0,
          attributes: { ...feature.attributes }
        }

        // 根据景点所属景区设置当前景区
        if (feature.attributes.OwnerScenic === '胶南灵山岛景区') {
          activeArea.value = 'erdihu'
        } else if (feature.attributes.OwnerScenic === '大公岛景区') {
          activeArea.value = 'yunmen'
        } else if (feature.attributes.OwnerScenic === '大泽山景区') {
          activeArea.value = 'bailang'
        }

        // 在地图上高亮显示
        highlightFeatureOnMap(feature)

        // 打开维修上报表单
        openReportForm(selectedFeature.value)
      }
    } catch (error) {
      console.error('查询指定景点失败', error)
    }
  }
}

// 页面加载完成后初始化地图
onMounted(async () => {
  await initMap()
  checkForSpecificPoint()
})
</script>

<style scoped lang="scss">
.maintenance-report-container {
  padding: 20px;
}

.maintenance-report-header {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-left: 4px solid #67c23a;
}

.header-actions {
  margin-bottom: 15px;
}

.maintenance-report-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.maintenance-report-header p {
  color: #606266;
  font-size: 14px;
}

.map-container {
  height: 400px;
  width: 100%;
  position: relative;
}

.map-card,
.area-select-card,
.scenic-list-card,
.selected-feature-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-feature-info {
  padding: 10px;
  text-align: center;
}

.selected-feature-info h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #303133;
}

.selected-feature-info p {
  color: #606266;
  font-size: 14px;
  margin-bottom: 15px;
}

.report-form {
  padding: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .maintenance-report-container {
    padding: 10px;
  }

  .map-container {
    height: 300px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
